package 栈的链表实现;

import java.util.Iterator;

public class Stack1<E> implements Iterable<E>{

    private int size;
    private final int capacity;
    private final Node<E> head = new Node<>(null, null);

    public Stack1(int capacity) {
        this.capacity = capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<>() {
            Node<E> p = head.next;
            @Override
            public boolean hasNext() {
                return p != null;
            }

            @Override
            public E next() {
                E value = p.value;
                p = p.next;
                return value;
            }
        };
    }

    static class Node<E> {
        E value;
        Node<E> next;

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }

    /**
     * 向栈顶压入元素
     * @param value 带压入值
     * @return 压入成功返回true, 否则返回false
     */
    public boolean push(E value) {
        if (isFull()) {
            return false;
        }
        head.next = new Node<>(value, head.next);
        size++;
        return true;
    }

    /**
     * 从栈顶弹出元素
     * @return 栈非空返回栈顶元素, 栈为空返回null
     */
    public E pop() {
        if (isEmpty()) {
            return null;
        }
        E value = head.next.value;
        head.next = head.next.next;
        size--;
        return value;
    }
    /**
     * 返回栈顶元素, 不弹出
     * @return 栈非空返回栈顶元素, 栈为空返回null
     */
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return head.next.value;
    }

    /**
     * 判断栈是否为空
     * @return 空返回true, 否则返回false
     */
    boolean isEmpty() {
        return size == 0;
    }

    /**
     * 判断栈是否为满
     * @return 满返回true, 否则返回false
     */
    Boolean isFull() {
        return size == capacity;
    }
}
